window.onload = initPage;
hasText = false;
currentUser = "";
lastUpdateTime = null;

function initPage() {
	// alert('test');
	/* bật chế độ design mode khiến iframe trở thành editor */
	initEditable();

	/* get current logined user */
	getcurrentUser();

	/* hàm thực hiện việc gửi text */
	document.getElementById("send-button").addEventListener("click", sendText,
			false);

	/* format text */
	document.getElementById("bold")
			.addEventListener("click", toggleBold, false);
	document.getElementById("italic").addEventListener("click", toggleItalic,
			false);
	document.getElementById("underline").addEventListener("click",
			toggleUnderline, false);
	document.getElementById("fontsize").addEventListener("change",
			toggleFontsize, false);
	document.getElementById("fontname").addEventListener("change",
			toggleFontname, false);

	/* hiện khung đổi màu chữ */
	document.getElementById("forecolor").addEventListener("click",
			forecolorClick, false);
	/* ẩn khung đổi màu chữ */
	document.addEventListener("click", dismissColorPalette, true);
	document.addEventListener("keypress", dismissColorPalette, true);
	document.getElementById("edit").contentDocument.addEventListener(
			"mousedown", dismissColorPalette, true);
	document.getElementById("edit").contentDocument.addEventListener(
			"mousedown", hideIconTable, true);
	document.getElementById("output").contentDocument.addEventListener(
			"mousedown", dismissColorPalette, true);
	document.getElementById("output").contentDocument.addEventListener(
			"mousedown", hideIconTable, true);

	/* event press enter to send text */
	document.getElementById("edit").contentDocument.addEventListener(
			"keypress", checkUserInput, true);

	/* hien bang chon cac icon */
	document.getElementById("button-choose-icon").addEventListener("click",
			showIconTable, false);

	/* them su kien chen cac icon */
	var icons = document.getElementById("select-icon").getElementsByTagName(
			"img");
	for ( var i = 0; i < icons.length; i++) {
		icons[i].addEventListener("click", insertIcon, false);
	}

}

/* bật chế độ edit của iframe */
function initEditable() {
	editor = document.getElementById('edit');
	// editor.getElementsByTagName("body")[0].style.lineHeight = "30";
	if (editor.contentDocument) {
		editorDoc = editor.contentDocument;
	} else {
		editorDoc = editor.contentWindow.document;
	}
	// editorBody là biến toàn cục
	editorBody = editorDoc.body;
	// tắt spell check
	if ('spellcheck' in editorBody) {
		editorBody.spellcheck = false;
	}

	if ('contentEditable' in editorBody) {
		editorBody.contentEditable = true;
	} else { // firefox trước phiên bản 3.0
		if ('designMode' in editorDoc) {
			editorDoc = "on";
		}
	}
}

function getcurrentUser() {
	request = createRequest();
	if (request === null) {
		alert("Khong the khoi tao XMLHttpRequest!");
	}
	var params = "action=getuser";
	request.onreadystatechange = setcurrentUser;
	request.open("POST", "/chat", true);
	request.setRequestHeader("Content-type",
			"application/x-www-form-urlencoded");
	request.setRequestHeader("Content-length", params.length);
	request.setRequestHeader("Connection", "close");
	request.send(params);
}

function setcurrentUser() {
	if (request.readyState === 4) {
		if (request.status === 200) {
			currentUser = request.responseText;
			console.log(currentUser);
			/* get list message before */
			getOldMessage();
		}
	}
}

/* thực hiện chèn các icon vào thẻ iframe */
function insertIcon() {
	editorDoc.execCommand('InsertImage', false, this.src);
	hideIconTable();
}

/* hiện bảng chọn các icon */
function showIconTable() {
	document.getElementById("select-icon").style.visibility = "visible";
}

/* ẩn bảng chọn các icon */
function hideIconTable() {
	document.getElementById("select-icon").style.visibility = "hidden";
}

/* làm đậm text */
function toggleBold() {
	editorDoc.execCommand("bold", false, null);
}

/* làm nghiêng text */
function toggleItalic() {
	editorDoc.execCommand("italic", false, null);
}

/* làm text gạch dưới */
function toggleUnderline() {
	editorDoc.execCommand("underline", false, null);
}

/* chỉnh fontsize */
function toggleFontsize() {
	editorDoc.execCommand("fontSize", false, document
			.getElementById("fontsize").value.toString());
}

/* chỉnh fontname */
function toggleFontname() {
	editorDoc.execCommand("fontName", false, document
			.getElementById("fontname").value.toString());
}

/* thực thiện việc hiển thị text lên khung chat */
function sendText() {
	var text = editorBody.innerHTML;
	console.log(text);
	if (text === "" || text === "<br />") {
		return;
	}
	var currentdate = new Date();
	var datetime = "Gui luc: " + currentdate.getDate() + "/"
			+ (currentdate.getMonth() + 1) + "/" + currentdate.getFullYear()
			+ " @ " + currentdate.getHours() + ":" + currentdate.getMinutes()
			+ ":" + currentdate.getSeconds();
	text1 = "<span style='color:sienna;' >" + currentUser + ": </span>" + text
			+ "<span style='float: right;'>" + datetime + "</span><br />";
	var outputPanel = document.getElementById("output");
	outputBody = outputPanel.contentDocument.getElementsByTagName("body")[0];
	outputBody.insertAdjacentHTML("beforeend", text1);
	editorBody.innerHTML = "";

	// save text to database
	saveMessage(text);
}
/* save message to database */
function saveMessage(text) {
	request = createRequest();
	if (request === null) {
		alert("Khong the khoi tao XMLHttpRequest!");
	}
	var params = "action=save&message=" + text;
	request.onreadystatechange = saveDone;
	request.open("POST", "/chat", true);
	request.setRequestHeader("Content-type",
			"application/x-www-form-urlencoded");
	request.setRequestHeader("Content-length", params.length);
	request.setRequestHeader("Connection", "close");
	request.send(params);
}

/* check if saving message successful */
function saveDone() {
	if (request.readyState === 4) {
		if (request.status === 200) {
			// alert(request.responseText);
		}
	}
}

/* get old message */
function getOldMessage() {
	request = createRequest();
	if (request === null) {
		alert("Khong the khoi tao XMLHttpRequest!");
	}
	var params = "action=getbefore";
	request.onreadystatechange = loadOldMessage;
	request.open("POST", "/chat", true);
	request.setRequestHeader("Content-type",
			"application/x-www-form-urlencoded");
	request.setRequestHeader("Content-length", params.length);
	request.setRequestHeader("Connection", "close");
	request.send(params);
}

/* load old message to chat view */
function loadOldMessage() {
	if (request.readyState === 4) {
		if (request.status === 200) {
			var outputPanel = document.getElementById("output");
			outputBody = outputPanel.contentDocument
					.getElementsByTagName("body")[0];
			data = JSON.parse(request.responseText);
			var len = data.length;
			for ( var i = 0; i < len; i++) {
				// console.log(data[i]);
				var currentdate = new Date(data[i].postedDate);
				var datetime = "Gui luc: " + currentdate.getDate() + "/"
						+ (currentdate.getMonth() + 1) + "/"
						+ currentdate.getFullYear() + " @ "
						+ currentdate.getHours() + ":"
						+ currentdate.getMinutes() + ":"
						+ currentdate.getSeconds();
				var temp = "<span style='color:sienna;' >" + data[i].username
						+ ": </span>" + data[i].message
						+ "<span style='float: right;'>" + datetime
						+ "</span><br />";
				outputBody.insertAdjacentHTML("beforeend", temp);
			}

			// set last update time = after load all old message
			lastUpdateTime = new Date();
			/* check updated message */
			checkUpdateMessage();
		}
	}
}

/* after 5s get message */
function checkUpdateMessage() {
	var temp = self.setInterval(function() {
		getNewMessage();
	}, 5000);
}

// get new message
function getNewMessage() {
	request = createRequest();
	if (request === null) {
		alert("Khong the khoi tao XMLHttpRequest!");
	}

	var params = "action=getupdate&time=" + lastUpdateTime.getTime();
	request.onreadystatechange = updateMessage;
	request.open("POST", "/chat", true);
	request.setRequestHeader("Content-type",
			"application/x-www-form-urlencoded");
	request.setRequestHeader("Content-length", params.length);
	request.setRequestHeader("Connection", "close");
	request.send(params);
}

/* update Message to chat view */
function updateMessage() {
	if (request.readyState === 4) {
		if (request.status === 200) {
			// set last update time to now
			lastUpdateTime = new Date();
			// console.log(request.responseText);
			var outputPanel = document.getElementById("output");
			outputBody = outputPanel.contentDocument
					.getElementsByTagName("body")[0];
			data = JSON.parse(request.responseText);
			var len = data.length;
			for ( var i = 0; i < len; i++) {
				// console.log(data[i]);
				var currentdate = new Date(data[i].postedDate);
				var datetime = "Gui luc: " + currentdate.getDate() + "/"
						+ (currentdate.getMonth() + 1) + "/"
						+ currentdate.getFullYear() + " @ "
						+ currentdate.getHours() + ":"
						+ currentdate.getMinutes() + ":"
						+ currentdate.getSeconds();
				var temp = "<span style='color:sienna;' >" + data[i].username
						+ ": </span>" + data[i].message
						+ "<span style='float: right;'>" + datetime
						+ "</span><br />";
				outputBody.insertAdjacentHTML("beforeend", temp);
			}
		}
	}
}

/* lấy tọa độ trái của một phần tử */
function getOffsetLeft(elem) {
	var mOffsetleft = elem.offsetLeft;
	var mOffsetParent = elem.offsetParent;
	while (mOffsetParent) {
		mOffsetleft += mOffsetParent.offsetLeft;
		mOffsetParent = mOffsetParent.offsetParent;
	}
	return mOffsetleft;
}

/* lấy tọa độ top */
function getOffsetTop(elem) {
	var mOffsetTop = elem.offsetTop;
	var mOffsetParent = elem.offsetParent;
	while (mOffsetParent) {
		mOffsetTop += mOffsetParent.offsetTop;
		mOffsetParent = mOffsetParent.offsetParent;
	}
	return mOffsetTop;
}

/* hiển thị bảng màu */
function showColorPalette() {
	var button = document.getElementById("forecolor");
	var palette = document.getElementById("colorpalette");
	palette.style.left = getOffsetLeft(button).toString() + "px";
	palette.style.top = (getOffsetTop(button) + button.offsetHeight - 10)
			.toString()
			+ "px";
	palette.style.visibility = "visible";
}

/* gọi hiển thị bảng màu */
function forecolorClick() {
	showColorPalette();
}

/* ẩn bảng màu đi */
function dismissColorPalette() {
	document.getElementById("colorpalette").style.visibility = "hidden";
}

/* check if user press 'Enter' to send text */
function checkUserInput(e) {
	if (e.keyCode === 13) {
		e.preventDefault();
		sendText();
	}
}